package basic

import (
	"fmt"
	"net/http"

	"github.com/gpmgo/gopm/modules/log"
)

/**
http server 遇到panic还无法宕机是受到保护的
http 处理error
http server 被保护不退出其实是被recover了所以
*/

func H(writer http.ResponseWriter, request *http.Request) error {

	// writer.Write([]byte(request.URL.Path))

	// http处理error 不用panic 这样也不好 我们需要把业务逻辑搞出去 然后通过errors来返回错误 由 http.Error消费
	http.Error(writer, "naocan", http.StatusBadGateway)

	//ioutil.ReadAll() // 读取所有的内容

	return nil
}

type AppHandler func(writer http.ResponseWriter, request *http.Request) error

func Wp(app AppHandler) func(writer http.ResponseWriter, request *http.Request) {
	return func(writer http.ResponseWriter, request *http.Request) {

		defer func() {
			e := recover()
			if e != nil {
				log.Error("error:", e)
				http.Error(writer, http.StatusText(http.StatusNotFound), http.StatusNotFound)
			}
		}()

		er := H(writer, request)

		panic(123)
		log.Warn("error") // 打印日志
		//switch  {
		//// er 是文件打开写入等等返回的错误可以用os.来找到相应的匹配方式 http.StatusText 不实用er.Error() 这样直接就暴露出去了
		//case os.IsNotExist(er):http.Error(writer, http.StatusText(http.StatusNotFound), http.StatusNotFound) // 文件不存在
		//default:
		//	http.Error(writer, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		//}

		fmt.Println(er)
	}
}

func BaseServer() {
	http.HandleFunc("/list", Wp(H))

	http.ListenAndServe("0.0.0.0:3456", nil)
}
